<template>
  <view class="profile-container">
    <!-- 顶部用户信息 -->
    <view class="user-header">
      <image class="user-bg" src="/static/logo.png" mode="aspectFill"></image>
      <view class="user-info" @tap="editProfile">
        <image class="avatar" :src="userInfo?.avatar" mode="aspectFill"></image>
        <view class="info-content">
          <text class="username">{{ userInfo?.nickname || userInfo?.username || '用户昵称' }}</text>
          <text class="user-id">ID: {{ userInfo?.id || '--' }}</text>
        </view>
      </view>

      <!-- 个人简介 -->
      <view class="user-bio">
        <text class="user-bio-text">{{ userInfo?.bio || '这个人很懒，还没有填写个人简介~' }}</text>
      </view>
      <!-- 数据统计 -->
      <view class="stats-row">
        <view class="stat-item" @tap="goToPage('works')">
          <text class="stat-num">{{ userInfo?.friendsCount || 0 }}</text>
          <text class="stat-label">好友</text>
        </view>
        <view class="stat-item" @tap="goToPage('followers')">
          <text class="stat-num">{{ userInfo?.followersCount || 0 }}</text>
          <text class="stat-label">粉丝</text>
        </view>
        <view class="stat-item" @tap="goToPage('following')">
          <text class="stat-num">{{ userInfo?.followingCount || 0 }}</text>
          <text class="stat-label">关注</text>
        </view>
        <view class="stat-item" @tap="goToPage('likes')">
          <text class="stat-num">{{ userInfo?.receivedLikesCount || 0 }}</text>
          <text class="stat-label">获赞</text>
        </view>
      </view>
    </view>

    <!-- 功能菜单 -->
    <scroll-view class="menu-scroll" scroll-y>
      <!-- 我的服务 -->
      <view class="menu-section">
        <view v-for="(item, index) in serviceMenu" :key="index" class="service-section">
          <view class="service-header">
            <view class="title-section">
              <text class="service-title">{{ item.label }}</text>
              <!-- 草稿箱显示切换标签 -->
              <view v-if="item.type === 'drafts'" class="tab-switcher">
                <text class="tab-item" :class="{ active: draftsTabActive === 'published' }"
                  @tap.stop="switchDraftsTab('published')">已发布({{ item.publishedWorks?.length || 0 }})</text>
                <text class="tab-divider">|</text>
                <text class="tab-item" :class="{ active: draftsTabActive === 'drafts' }"
                  @tap.stop="switchDraftsTab('drafts')">草稿箱({{ item.works?.length || 0 }})</text>
              </view>
              <text v-else class="service-count">（{{ item.works?.length || 0 }}）</text>
            </view>
            <text class="view-all-btn" @tap.stop="viewAll(item)">查看全部</text>
          </view>
          <scroll-view class="service-cards-scroll" scroll-x :show-scrollbar="false">
            <view class="service-cards-container">
              <!-- 有数据时显示作品卡片 -->
              <view v-for="(work, workIndex) in getDisplayWorks(item)" :key="workIndex" class="work-card"
                @tap="goToWorkDetail(work)">
                <view class="work-thumbnail">
                  <image v-if="work.thumbnail" class="work-image" :src="work.thumbnail" mode="aspectFill"></image>
                  <view v-else class="work-image-placeholder">
                    <text class="placeholder-icon">{{ item.icon }}</text>
                  </view>
                  <view v-if="work.duration" class="work-duration">{{ work.duration }}</view>
                </view>
                <view class="work-info">
                  <text class="work-title">{{ work.title }}</text>
                  <text class="work-subtitle">{{ work.subtitle || '生活记' }}</text>
                </view>
              </view>
              <!-- 没有数据时显示空占位卡片 -->
              <view v-if="getDisplayWorks(item).length === 0" class="work-card work-card-empty">
                <view class="work-thumbnail">
                  <view class="work-image-placeholder empty-placeholder">
                    <text class="placeholder-icon">{{ item.icon }}</text>
                  </view>
                </view>
                <view class="work-info">
                  <text class="work-title empty-title">{{ getEmptyText(item) }}</text>
                  <text class="work-subtitle empty-subtitle">快去添加吧~</text>
                </view>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>

      <!-- 通用设置 -->
      <view class="menu-section">
        <view class="section-title">通用设置</view>
        <view class="menu-list">
          <view v-for="(item, index) in settingMenu" :key="index" class="menu-item" @tap="onMenuTap(item)">
            <text class="menu-icon">{{ item.icon }}</text>
            <text class="menu-label">{{ item.label }}</text>
          </view>
        </view>
      </view>

      <!-- 其他 -->
      <view class="menu-section">
        <view class="menu-list">
          <view v-for="(item, index) in otherMenu" :key="index" class="menu-item" @tap="onMenuTap(item)">
            <text class="menu-icon">{{ item.icon }}</text>
            <text class="menu-label">{{ item.label }}</text>
          </view>
        </view>
      </view>

      <!-- 退出登录 -->
      <view class="logout-section">
        <view class="logout-btn" @tap="handleLogout">
          <text class="logout-text">退出登录</text>
        </view>
      </view>
    </scroll-view>

    <!-- 自定义 TabBar -->
    <custom-tabbar :current="3" />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import CustomTabbar from '@/components/custom-tabbar/custom-tabbar.vue'
import { getMyCollections, getMyDrafts, getMyPublishedWorks, type WorkInfo, WorkCategoryEnum } from '@/api/works'
import { TOKEN_KEY, USER_INFO_KEY } from '@/config/env'
import { useUser } from '@/composables/useUser'

// 用户信息
const userInfo = ref<{
  id?: number
  avatar?: string
  nickname?: string
  username?: string
  bio?: string
  friendsCount?: number
  followersCount?: number
  followingCount?: number
  receivedLikesCount?: number
}>({
  avatar: '',
  nickname: '',
  username: '',
  bio: '',
  friendsCount: 0,
  followersCount: 0,
  followingCount: 0,
  receivedLikesCount: 0
})

// 我的服务菜单
const serviceMenu = ref([
  {
    icon: '⭐',
    label: '收藏列表',
    type: 'favorites',
    works: [] as any[]
  },
  {
    icon: '📝',
    label: '作品',
    type: 'drafts',
    badge: '0',
    works: [] as any[],
    publishedWorks: [] as any[] // 已发布的作品
  }
])

// 草稿箱切换标签状态
const draftsTabActive = ref<'published' | 'drafts'>('drafts')

// 加载状态
const loading = ref({
  favorites: false,
  drafts: false
})

// 将作品信息转换为卡片格式
const formatWorkToCard = (work: WorkInfo) => {
  const categoryMap: Record<string, string> = {
    [WorkCategoryEnum.FOOD]: '美食',
    [WorkCategoryEnum.HEALTH]: '养生',
    [WorkCategoryEnum.TRAVEL]: '旅游'
  }

  return {
    id: work.id,
    title: work.title,
    subtitle: categoryMap[work.category] || '生活记',
    thumbnail: work.mediaType === 'image'
      ? (work.imagesUrls && work.imagesUrls.length > 0 ? work.imagesUrls[0] : null)
      : (work.videoCover || null),
    duration: work.mediaType === 'video' ? null : null // 视频时长需要额外处理
  }
}

// 加载收藏列表
const loadCollections = async () => {
  const token = uni.getStorageSync(TOKEN_KEY)
  if (!token) {
    return
  }

  try {
    loading.value.favorites = true
    const response = await getMyCollections(1, 10)
    const favoritesIndex = serviceMenu.value.findIndex(item => item.type === 'favorites')
    if (favoritesIndex !== -1) {
      serviceMenu.value[favoritesIndex].works = response.data.map(formatWorkToCard)
    }
  } catch (error: any) {
    console.error('加载收藏列表失败:', error)
  } finally {
    loading.value.favorites = false
  }
}

// 加载草稿箱
const loadDrafts = async () => {
  const token = uni.getStorageSync(TOKEN_KEY)
  if (!token) {
    return
  }

  try {
    loading.value.drafts = true
    const response = await getMyDrafts(1, 10)
    const draftsIndex = serviceMenu.value.findIndex(item => item.type === 'drafts')
    if (draftsIndex !== -1) {
      serviceMenu.value[draftsIndex].works = response.data.map(formatWorkToCard)
      serviceMenu.value[draftsIndex].badge = String(response.total)
    }
  } catch (error: any) {
    console.error('加载草稿箱失败:', error)
  } finally {
    loading.value.drafts = false
  }
}

// 加载已发布的作品
const loadPublishedWorks = async () => {
  const token = uni.getStorageSync(TOKEN_KEY)
  if (!token) {
    return
  }

  try {
    loading.value.drafts = true
    const response = await getMyPublishedWorks(1, 10)
    const draftsIndex = serviceMenu.value.findIndex(item => item.type === 'drafts')
    if (draftsIndex !== -1) {
      serviceMenu.value[draftsIndex].publishedWorks = response.data.map(formatWorkToCard)
    }
  } catch (error: any) {
    console.error('加载已发布作品失败:', error)
  } finally {
    loading.value.drafts = false
  }
}

// 切换草稿箱标签
const switchDraftsTab = (tab: 'published' | 'drafts') => {
  if (draftsTabActive.value === tab) {
    return
  }
  draftsTabActive.value = tab

  // 如果切换到"作品"且还没有加载过已发布作品，则加载
  if (tab === 'published') {
    const draftsIndex = serviceMenu.value.findIndex(item => item.type === 'drafts')
    const draftsItem = draftsIndex !== -1 ? serviceMenu.value[draftsIndex] : null
    if (draftsItem && draftsItem.publishedWorks && draftsItem.publishedWorks.length === 0) {
      loadPublishedWorks()
    }
  }
}

// 获取当前显示的作品列表
const getDisplayWorks = (item: any) => {
  if (item.type === 'drafts') {
    return draftsTabActive.value === 'published' ? item.publishedWorks : item.works
  }
  return item.works
}

// 获取空状态文本
const getEmptyText = (item: any) => {
  if (item.type === 'favorites') {
    return '暂无收藏'
  } else if (item.type === 'drafts') {
    return draftsTabActive.value === 'published' ? '暂无作品' : '暂无草稿'
  }
  return '暂无内容'
}

// 获取用户信息
const getUserInfo = () => {
  try {
    const storedUserInfo = uni.getStorageSync(USER_INFO_KEY)
    if (storedUserInfo) {
      const parsedUserInfo = typeof storedUserInfo === 'string'
        ? JSON.parse(storedUserInfo)
        : storedUserInfo

      console.log('解析后的用户信息:', parsedUserInfo)

      // 更新用户信息，确保所有字段都有值
      userInfo.value = {
        id: parsedUserInfo.id,
        avatar: parsedUserInfo.avatar || '',
        nickname: parsedUserInfo.nickname || parsedUserInfo.username || '',
        username: parsedUserInfo.username || '',
        bio: parsedUserInfo.bio || '',
        friendsCount: parsedUserInfo.friendsCount || 0,
        followersCount: parsedUserInfo.followersCount || 0,
        followingCount: parsedUserInfo.followingCount || 0,
        receivedLikesCount: parsedUserInfo.receivedLikesCount || 0
      }

      console.log('更新后的 userInfo:', userInfo.value)
      return userInfo.value
    } else {
      // 没有用户信息，提示登录
      const token = uni.getStorageSync(TOKEN_KEY)
      if (!token) {
        uni.showModal({
          title: '提示',
          content: '请先登录',
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/login/login'
              })
            }
          }
        })
      }
      return null
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    uni.showToast({
      title: '获取用户信息失败',
      icon: 'none'
    })
    return null
  }
}

// 页面加载时获取数据
onMounted(() => {
  getUserInfo()
  loadCollections()
  loadDrafts()
  loadPublishedWorks()
})

// 页面显示时刷新数据（每次从其他页面返回或点击底部导航栏时触发）
onShow(() => {
  getUserInfo()
  loadCollections()
  loadDrafts()
  // 如果当前显示的是"作品"标签，也刷新已发布作品
  if (draftsTabActive.value === 'published') {
    loadPublishedWorks()
  }
})

// 通用设置菜单
const settingMenu = ref([
  { icon: '🌙', label: '深色模式', type: 'darkMode' },
  { icon: '🔔', label: '消息通知', type: 'notifications' }
])

// 其他菜单
const otherMenu = ref([
  { icon: '📞', label: '联系客服', type: 'contact' },
  { icon: 'ℹ️', label: '关于我们', type: 'about' }
])

const { logout: logoutUser } = useUser()

// 编辑资料
const editProfile = () => {
  uni.navigateTo({
    url: '/pages/myInfo/myInfo'
  })
}

// 跳转页面
const goToPage = (type: string) => {
  if (type === 'works') {
    uni.navigateTo({
      url: '/pages/addFriend/addFriend?tab=list'
    })
    return
  }
  uni.showToast({
    title: `查看${type}`,
    icon: 'none'
  })
}

// 菜单点击
const onMenuTap = (item: any) => {
  uni.showToast({
    title: item.label,
    icon: 'none'
  })
}

// 查看全部
const viewAll = (item: any) => {
  if (item.type === 'favorites') {
    // TODO: 跳转到收藏列表页面
    uni.showToast({
      title: '查看全部收藏',
      icon: 'none'
    })
  } else if (item.type === 'drafts') {
    // TODO: 跳转到草稿箱页面
    uni.showToast({
      title: '查看全部草稿',
      icon: 'none'
    })
  }
}

// 跳转到作品详情
const goToWorkDetail = (work: any) => {
  uni.navigateTo({
    url: `/pages/detail/detail?id=${work.id}`
  })
}

// 退出登录
const handleLogout = () => {
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    success: async (res) => {
      if (!res.confirm) return
      uni.showLoading({
        title: '正在退出...',
        mask: true
      })
      try {
        await logoutUser(false)
        uni.showToast({
          title: '已退出登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/login/login'
          })
        }, 600)
      } catch (error) {
        console.error('退出登录失败:', error)
        uni.showToast({
          title: '退出失败，请重试',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    }
  })
}
</script>

<style scoped>
.profile-container {
  width: 100%;
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  padding-bottom: 100rpx;
}

/* 用户头部 */
.user-header {
  background-color: #fff;
  position: relative;
  padding-top: 20px;
}

.user-bg {
  width: 100%;
  height: 300rpx;
  opacity: 0.3;
}

.user-info {
  position: absolute;
  top: 120rpx;
  left: 30rpx;
  right: 30rpx;
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.avatar {
  width: 160rpx;
  height: 160rpx;
  border-radius: 50%;
  border: 4rpx solid #fff;
}

.info-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.username {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.user-id {
  font-size: 24rpx;
  color: #999;
}

.edit-btn {
  padding: 10rpx 30rpx;
  background-color: #4A90E2;
  border-radius: 40rpx;
}

.edit-text {
  font-size: 24rpx;
  color: #fff;
}

/* 个人简介 */
.user-bio {
  font-size: 24rpx;
  color: #666;
  line-height: 1.5;
  text-align: center;
  word-break: break-all;
  position: absolute;
  top: 300rpx;
  left: 50rpx;
  right: 30rpx;
  display: flex;
  align-items: center;
}

.user-bio-text {
  font-size: 24rpx;
  color: #999;
  line-height: 1.5;
  text-align: center;
  word-break: break-all;
  line-clamp: 2;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 数据统计 */
.stats-row {
  display: flex;
  padding: 40rpx 30rpx 30rpx;
}

.stat-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10rpx;
}

.stat-num {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.stat-label {
  font-size: 24rpx;
  color: #999;
}

/* 菜单滚动区 */
.menu-scroll {
  flex: 1;
  overflow-y: auto;
}

/* 菜单区块 */
.menu-section {
  margin-top: 20rpx;
}

.section-title {
  font-size: 28rpx;
  color: #999;
  padding: 20rpx 30rpx 10rpx;
}

/* 我的服务 - 卡片列表 */
.service-section {
  margin-bottom: 30rpx;
  background-color: #fff;
  padding-bottom: 20rpx;
}

.service-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 30rpx 20rpx;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.service-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.service-count {
  font-size: 28rpx;
  color: #999;
  font-weight: normal;
}

/* 切换标签样式 */
.tab-switcher {
  display: flex;
  align-items: center;
  gap: 8rpx;
  margin-left: 8rpx;
}

.tab-item {
  font-size: 26rpx;
  color: #999;
  padding: 4rpx 0;
  transition: color 0.3s;
}

.tab-item.active {
  color: #4A90E2;
  font-weight: 500;
}

.tab-divider {
  font-size: 24rpx;
  color: #ddd;
}

.view-all-btn {
  font-size: 26rpx;
  color: #999;
  padding: 8rpx 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 50rpx;
}

.service-cards-scroll {
  width: 100%;
  white-space: nowrap;
}

.service-cards-container {
  display: flex;
  gap: 20rpx;
  padding: 0 30rpx;
}

.work-card {
  flex-shrink: 0;
  width: 280rpx;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.work-thumbnail {
  position: relative;
  width: 100%;
  height: 200rpx;
  border-radius: 12rpx;
  overflow: hidden;
  background-color: #f0f0f0;
}

.work-image {
  width: 100%;
  height: 100%;
}

.work-image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.placeholder-icon {
  font-size: 60rpx;
  opacity: 0.5;
}

.work-duration {
  position: absolute;
  bottom: 8rpx;
  right: 8rpx;
  background-color: rgba(0, 0, 0, 0.6);
  color: #fff;
  font-size: 20rpx;
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
}

.work-info {
  display: flex;
  flex-direction: column;
  gap: 6rpx;
}

.work-title {
  font-size: 26rpx;
  color: #333;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.work-subtitle {
  font-size: 22rpx;
  color: #999;
}

/* 空占位卡片样式 */
.work-card-empty {
  opacity: 0.6;
  pointer-events: none;
}

.empty-placeholder {
  background: linear-gradient(135deg, #f0f0f0 0%, #e0e0e0 100%);
}

.empty-placeholder .placeholder-icon {
  opacity: 0.3;
}

.empty-title {
  color: #999 !important;
  font-weight: normal !important;
}

.empty-subtitle {
  color: #ccc !important;
}

.menu-list {
  background-color: #fff;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  position: relative;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-icon {
  font-size: 40rpx;
  margin-right: 20rpx;
}

.menu-label {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.menu-badge {
  background-color: #ff4444;
  color: #fff;
  font-size: 20rpx;
  padding: 4rpx 10rpx;
  border-radius: 20rpx;
  margin-right: 10rpx;
}

.menu-arrow {
  font-size: 24rpx;
  color: #ccc;
}

/* 退出登录 */
.logout-section {
  padding: 40rpx 30rpx;
}

.logout-btn {
  background-color: #fff;
  padding: 30rpx;
  border-radius: 20rpx;
  text-align: center;
}

.logout-text {
  font-size: 28rpx;
  color: #ff4444;
}
</style>
